<script setup lang="ts">
import localesList from '@intlify/vite-plugin-vue-i18n/messages';
import { loadVoLteResourceList } from '@/utils/format';
import { throttle } from '@/utils/format';
import { isDark, toggleDark } from '@/utils/dark';

// 使用pinia
import system from '@/store/system';
import nocache from './store/nocache';
import { getCurrentInstance } from "vue";
import userinfo from './store/userinfo';

const piniaSystem = system(); //系统设置
const piniaNocache = nocache(); // 常用非缓存状态
const piniaUserinfo = userinfo();

const { t, availableLocales, locale } = useI18n();
const vantTheme:any = computed(()=> piniaSystem.getDarkTheme ? 'dark' : 'light');

// 创建Socket链接
const global:any = getCurrentInstance()?.appContext.config.globalProperties;

const socketEvent = () => {
  piniaNocache.setSocket(new global.$Socket({
    url: import.meta.env.VITE_APP_SERVER_SOCKET_HALL,
    heartMsg: null,
    isLogin: true,
  }));

  if(piniaNocache.getSocket){
    piniaNocache.getSocket.on("connect", () => {
      piniaNocache.getSocket.send({ content: {}, contentType: 51 })
    });

    piniaNocache.getSocket.on("message", (data:any) => {
      const response:any = JSON.parse(data);
      response.content = JSON.parse(response.content || "{}");
      console.log("response.contentType===============", response.contentType)
      if(response.contentType == 4){
        // 红包消息
        console.log("红包消息", response)
      }else if(response.contentType == 300){
        // 屏蔽消息
        console.log("屏蔽消息", response)
      }else if(response.contentType == 400){
        // 禁言消息
        console.log("禁言消息", response)
      }else if(response.contentType == 500){
        // 聊天禁止发送消息
        console.log("聊天禁止发送消息", response)
      }else if(response.contentType == 8){
        // notice
        console.log("通知", response);
        piniaUserinfo.queryNoticeAndEmail();
        global.message(t('home.newNotice'));
      }else if(response.contentType == 9){
        // email
        console.log("邮件", response)
        piniaUserinfo.queryNoticeAndEmail();
        global.message(t('home.newEmail'));
      }else if(response.contentType == 51){
        // 第一次未登录时获取默认的货币
        if(response.content && response.content.wallet){
          piniaUserinfo.setWallet(response.content.wallet);
        }
      }else if(response.contentType == 12){
        // 12 在线人数
        console.log("12", response)
      }else if(response.contentType == 13){
        // 13
        console.log("13", response)
      }else if(response.contentType == 14){
        // 14
        console.log("14", response)
      }else if(response.contentType == 50){
        // 50
        console.log("50充钱到账通知", response);
        piniaUserinfo.queryWallet();
        if(response.content && response.content.changeMoney){
          if(response.content.changeMoney < 0){
            // 扣钱
            global.message(`${t('home.newCurrencyReduce')} ${t('RescueFund.text10')}: ${Math.abs(response.content.changeMoney)}` , {
              type: 'danger'
            });
          }else{
            // 加钱
            global.message(t(`${t('home.newCurrency')} ${t('RescueFund.text10')}: ${Math.abs(response.content.changeMoney)}`));
          }
        }
      }else if(response.contentType == 995){
        // 登录被挤下去
        console.log("登录被挤下去", response)
        piniaUserinfo.logout();
      }else if(response.contentType == 999){
        // 999
        console.log("999", response)
      }else if(response.contentType == 21){
        // 21 充值 体现 首充 成功
        console.log("21 充值 体现 首充 成功", response)
      }else if(response.contentType == 22){
        // 22
        console.log("22", response)
      }else if(response.contentType == 23){
        // jackpotMoney
        console.log("23排行榜", response.content)
        piniaNocache.setJackPot(response.content);
      }
    });
  }
}

watch(
  () => piniaUserinfo.getHaslogged,
  (val, preVal) => {
    console.log('登录变化', val)
    if(val){
      // 登录成功，链接socket
      socketEvent();
    }else{
      // 退出登录
      console.log(piniaNocache.getSocket)
    }
  },
  { immediate: true, deep: true },
);


// 设置主题
if(piniaSystem.getDarkTheme !== isDark.value){
  toggleDark();
}

// 设置语言
locale.value = piniaSystem.getLang.locale || 'en-US';

const toJson = (json: any) => {
  let result:any = {};
  for (const key in json) {
    if (Object.prototype.hasOwnProperty.call(json, key)) {
      const element = json[key];
      if(element.source){
        result[key] = element.source;
      }else{
        result[key] = toJson(element);
      }
    }
  }
  return result;
}

const elementlocale = computed(()=>{
  const obj = {
    name: locale.value,
    el: toJson(localesList[locale.value].lang.el)
  };
  return obj;
});

// 设置字体大小
const setSize = () => {
  const deviceWidth = document.documentElement.clientWidth;
  const standardWidth = deviceWidth > 750 ? 1500 : 750;
  const fontSize = (deviceWidth * 1) / standardWidth + "px";
  document.documentElement.style.fontSize = deviceWidth > 1500 ? '1px' : fontSize;
};

setSize();
window.addEventListener('resize', throttle(setSize, 0.3));

</script>

<template>
  <VanOverlay :show="piniaNocache.getLoading" class="van-global-loading">
    <VanLoading vertical>
      <template #icon>
        <VanIcon name="underway-o" size="30" />
      </template>
      Loading...
    </VanLoading>
  </VanOverlay>
  <ElConfigProvider :locale="elementlocale">
    <VanConfigProvider :theme="vantTheme">
      <RouterView></RouterView>
    </VanConfigProvider>
  </ElConfigProvider>
</template>

